<template>
	<om-page title="登录">
		<view class="padding-xl text-center text-xxl bg-steelblue">欢迎登录OM系统</view>
		<view class="content">
			<!-- <view class="org_name_cls">{{ orgName }}</view> -->
			<view class="input-group">
				<view class="input-row border">
					<text class="title">账号：</text>
					<m-input class="m-input" type="text" clearable focus v-model="mobile" placeholder="请输入账号"></m-input>
				</view>
				<view class="input-row">
					<text class="title">密码：</text>
					<m-input type="password" displayable v-model="password" placeholder="请输入密码"></m-input>
				</view>
			</view>
			<view class="btn-row"><button type="primary" class="primary" @tap="ulogin">登录</button></view>
			<view v-if="loginTips">
				<uni-card mode="basic" isFull style="border: none;">
					<text style="font-size: smaller;color: #19be6b;">此为演示数据登录界面，若您已有所属组织，请使用微信扫一扫“OM掌上通”二维码登录！</text>
				</uni-card>
			</view>
		</view>
	</om-page>
</template>

<script>
import md5 from '@/static/js/md5.js';
import { mapState, mapActions } from 'pinia';
import { useLoginUserStore } from '@/stores/login-user.js'
const app = getApp();
export default {
	data() {
		return {
			login_org: 'OM系统',
			loginTips: false,
			mobile: '',
			password: ''
		};
	},
	computed: mapState(useLoginUserStore,[
		'forcedLogin'
		// #ifdef MP-WEIXIN
		,
		'openid',
		'orgCode',
		'orgList',
		'db',
		'orgName'
		// #endif
		]),
	methods: {
		...mapActions(useLoginUserStore,[
			'login','setOrgName'
			// #ifdef MP-WEIXIN
			,'setOrgCode','setOrgList','setSubUrl','setOpenid'
			// #endif
			]),
		ulogin() {
			let _that = this;
			if (!_that.mobile) {
				_that.data.alert('账号不能为空');
				return;
			}
			if (!_that.password) {
				_that.data.alert('密码不能为空');
				return;
			}
			uni.showLoading();
			wx.login({
				success(res) {
					if (res.code) {
						_that.requestLogin(res.code);
					}
				}
			});
		},
		requestLogin(code) {
			let _that = this
			_that.om
				.request(
					'wxlogin/doLogin2',
					{
						code: code,
						orgCode: _that.orgCode,
						mobile: _that.mobile,
						password: md5.hex_md5(_that.password)
					},
					'post',
					true
				)
				.then(res => {
					if(res.succeed){
						_that.dbVerify(res)
					}else{
						_that.om.toast(res.msg)
					}
				});
		},
		dbVerify(d){
			let _that = this
			uni.hideLoading()
			let response = d.value
			_that.db
				.collection('accounts')
				.where({
					_openid: _that.openid
				})
				.get()
				.then(res2 => {
					_that.openMain(response,res2)
				})
			
		},
		openMain(response, res2){
				let _that = this
				// res.data 是一个包含集合中有权限访问的所有记录的数据，不超过 20 条
				if (res2.data.length) {
					if (res2.data.length > 1) {
						console.log('获取到一个用户的多条绑定信息(只保留最后一条)：' + JSON.stringify(res2.data));
						for (var i = 0; i < res2.data.length - 1; i++) {
							_that.db
								.collection('accounts')
								.doc(res2.data[i]._id)
								.remove();
						}
					}
					var needUpdateFlag = true;
					var orges = res2.data[0].orges;
					for (var i = 0; i < orges; i++) {
						var org = orges[i];
						if (org.orgCode === _that.orgCode) {
							needUpdateFlag = false;
						}
					}
					if (needUpdateFlag) {
						//在多组织任职时，只更新所属组织
						const _ = _that.db.command;
						_that.db
							.collection('accounts')
							.doc(res2.data[0]._id)
							.update({
								// data 传入需要局部更新的数据
								data: {
									orges: _.push({
										userid: response.userid,
										username: response.username,
										orgCode: response.orgCode,
										orgname: response.orgname,
										createTime: _that.db.serverDate()
									})
								},
								success() {
									_that.login(response)
									uni.switchTab({
										url: '/pages/main/main/main'
									});
								},
								fail: function(fail) {
									console.log(fail);
								}
							});
					} else {
						//以防万一，正常不会跳进来
						_that.login(response)
						uni.switchTab({
							url: '/pages/main/main/main'
						});
					}
				} else {
					//还没有该用户时，执行新增
					_that.db.collection('accounts').add({
						data: {
							orges: [
								{
									userid: response.userid,
									username: response.username,
									orgCode: response.orgCode,
									orgname: response.orgname,
									createTime: _that.db.serverDate()
								}
							]
						},
						success(res4) {
							_that.login(response)
							uni.switchTab({
								url: '/pages/main/main/main'
							});
						},
						fail: function(res5) {}
					});
				}
			
		}
	},
	onLoad(options) {
		 let _that = this
		if (options.loginTips){
		  _that.loginTips = options.loginTips
		}
	}
};
</script>

<style></style>
